package com.situ.mall.controller.back;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import com.situ.mall.util.ImageServerUtil;
import com.situ.mall.util.QiNiuUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.situ.mall.util.JSONResult;

@Controller
public class UploadController {
	
	@ResponseBody
	@RequestMapping("/uploadImg.action")
	public JSONResult uploadImg(MultipartFile file) throws IOException {
		// 文件得名字要返回到前台表单，在insert时候插入数据库
		String newFileName = "";
		if (ImageServerUtil.IMG_SERVER == ImageServerUtil.QINIU) {
			newFileName = QiNiuUtil.uploadImage(file.getBytes());
		} else {
			newFileName = uploadToLocal(file);
		}
		return JSONResult.success("", newFileName);
	}

	private String uploadToLocal(MultipartFile file) {
		String fileName = file.getOriginalFilename();
		System.out.println(fileName);
		String name = UUID.randomUUID().toString().replace("-", "");
		String extension = FilenameUtils.getExtension(fileName);
		String newFileName = name + "." + extension;
		System.out.println(newFileName);
		String filePath = "D:\\pic\\" + newFileName;
		try {
			file.transferTo(new File(filePath));
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return newFileName;
	}
}
